import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:qunaimedical/utils/log_util.dart';
import 'package:qunaimedical/values/configs.dart';

class IMUtils {
  IMUtils._();

  static final String _tag = 'ease';
  static final String _password = "000000";

  static Future<void> initIMSDK() async {
    EMOptions options = EMOptions(
      appKey: Configs.easeIMAppKey_PROD,
    );
    await EMClient.getInstance.init(options);
  }

  static Future<void> signIn(String _userId) async {
    await EMClient.getInstance.login(_userId, _password);
    _addLogToConsole("sign in succeed, username: $_userId");
  }

  static void signOut() async {
    try {
      await EMClient.getInstance.logout(true);
      _addLogToConsole("sign out succeed");
    } on EMError catch (e) {
      _addLogToConsole(
          "sign out failed, code: ${e.code}, desc: ${e.description}");
    }
  }

  static Future<bool> signUp(String userId) async {
    if (userId.isEmpty) {
      _addLogToConsole("username or password is null");
      return false;
    }

    try {
      _addLogToConsole("begin create account...");
      await EMClient.getInstance.createAccount(userId, _password);
      _addLogToConsole("create account succeed, userId: $userId");
      return true;
    } on EMError catch (e) {
      _addLogToConsole(
          "create account failed, code: ${e.code}, desc: ${e.description}");
    }
    return false;
  }

  static void _addLogToConsole(String log) {
    Log.d(_tag, _timeString + ": " + log);
  }

  static String get _timeString {
    return DateTime.now().toString().split(".").first;
  }
}
